package com.hakim.wfb.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

//@Configuration
//public class WebConfigBeans {
//
//    @Autowired
//    private RequestMappingHandlerAdapter handlerAdapter;
//
//    /**
//     * 增加字符串转日期的功能
//     */
//    @PostConstruct
//    public void initEditableValidation() {
//        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
//                .getWebBindingInitializer();
//
//        if (initializer.getConversionService() != null) {
//            GenericConversionService genericConversionService = (GenericConversionService) initializer
//                    .getConversionService();
//            genericConversionService.addConverter(new StringToDateConverter());
//        }
//
//    }
//}

@Configuration
public class WebConfigBeans extends WebMvcConfigurerAdapter {

//    @Override
//    public void addFormatters(FormatterRegistry registry) {
//        registry.addConverter(new StringToDateConverter());
//    }

//    @Bean
//    public StringToDateConverter stringToDateConverter() {
//        return new StringToDateConverter();
//    }

    @Bean(name = "conversionService")
    public ConversionService getConversionService() {

        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        Set<Converter> converters = new HashSet<Converter>();

        //add the converter
        converters.add(new StringToDateConverter());

        bean.setConverters(converters);
        return bean.getObject();
    }

}
